package admin

import (
	"gitee.com/chejiangyi/bsfgo/core/utils"
	"gitee.com/chejiangyi/bsfgo/demo/domain/auto_models"
	"gitee.com/chejiangyi/bsfgo/demo/service/dals"
	"gitee.com/chejiangyi/bsfgo/demo/web/controller/base"
	"gitee.com/chejiangyi/bsfgo/gin2"
	"github.com/gin-gonic/gin"
	"time"
)

type UserController struct {
	base.BaseAdminWebController
}

func (m *UserController) Index(c *gin.Context) {
	defer m.CatchHtmlError(c)
	m.CheckUserAuth(c)
	data := gin.H{}
	var totalSize int64
	name := m.GetParamAddData(c, data, "name", "").(string)
	createTimeFrom := m.GetParamAddData(c, data, "createTimeFrom", "").(string)
	createTimeTo := m.GetParamAddData(c, data, "createTimeTo", "").(string)
	pageIndex := m.GetParamAddData(c, data, "pageIndex", 1).(int)
	pageSize := m.GetParamAddData(c, data, "pageSize", 10).(int)

	data["list"] = dals.DbUserDal.Search(m.GetConn(), name, createTimeFrom, createTimeTo, pageIndex, pageSize, &totalSize)
	gin2.NewPager1V2(pageIndex, utils.ConvertUtil.ToInt(totalSize), pageSize).SetData(data)
	m.Html(c, "user/index.html", data)
}

func (m *UserController) Edit(c *gin.Context) {
	defer m.CatchHtmlError(c)
	m.CheckUserAuth(c)
	id := m.GetParam(c, "id", 0).(int)
	model := dals.DbUserDal.GetById(m.GetConn(), id)
	data := gin.H{"model": model}
	//panic(base2.NewBsfError("cccc測試"))
	m.Html(c, "user/edit.html", data)
}

func (m *UserController) Save(c *gin.Context) {
	defer m.CatchJsonError(c)
	m.CheckUserAuth(c)
	id := m.GetParam(c, "id", 0).(int)
	name := m.GetParam(c, "name", "").(string)
	psd := m.GetParam(c, "psd", "").(string)
	var user *auto_models.User
	if id > 0 {
		user = dals.DbUserDal.GetById(m.GetConn(), id)
	} else {
		user.CreateTime = time.Now()
	}
	user.Name = name
	user.Psd = psd
	dals.DbUserDal.Update(m.GetConn(), user)
	m.JsonSuccess(c, "")
}
